/*
 * @Description: 公交定制页面
 * @Author: buwei.huang
 * @Date: 2019-07-09 18:08:34
 * @Last Modified by: ziwei.ma
 * @Last Modified time: 2019-10-30 16:21:57
 */
<template>
  <div
    class="app_wrap"
    :class="isOverflow ? 'overflowHidden' : ''"
  >
    <!-- <title-bar @setHeight="setHeight" /> -->
    <div
      class="wrap"
      v-show="isShowImgBg"
    >
      <img
        class="img_bg"
        src="./assets/title_bg.png"
      />
      <div class="customBus_content">
        <!-- 选择地点 -->
        <edit-info
          :type="1"
          :dateValue="dateValue"
          @selectPicker="selectPicker"
        />
        <!-- 选择日期 -->
        <edit-info
          :type="2"
          :dateValue="dateValue"
          @selectPicker="selectPicker"
          @clearDateEnd="clearDateEnd"
          @addDateEnd="addDateEnd"
        />
        <!-- 编辑文本 -->
        <edit-info
          ref="edit_textarea"
          :type="3"
          @getTextareaValue="getTextareaValue"
          @click.native="onRemark"
        />
      </div>
      <!-- btn -->
      <div class="btn_onSubmit_wrap">
        <button
          class="fontsize32 btn_onSubmit"
          v-show="isShowImgBg"
          @click="onSubmit()"
        >提交</button>
      </div>
    </div>
    <!-- 日期选择器 -->
    <date-picker
      :titleText="titleText"
      :pickerConfig="pickerConfig"
      @getValue="getValue"
      @onOverflow="onOverflow"
      ref="datePicker"
    />
    <!-- Toast弹框 -->
    <toast-alert
      ref="toastAlert"
      :msgText="msgText"
      :success="success"
      @onOverflow="onOverflow"
    />
    <!-- 备注弹框 -->
    <mock-remark
      ref="remark"
      :textValue="textareaValue"
      @onOverflow="onOverflow"
      @setTextareaValue="setTextareaValue"
    />
  </div>
</template>

<script>
import Remark from '../../../components/nonstopLIne/remark'
import TitleBar from './components/TitleBar'
import EditInfo from './components/EditInfo'
import DatePicker from '@/components/DatePicker'
import ToastAlert from '@/components/ToastAlert'
import { getStationList, onAddCustomDemand } from './api/api.js'
import { verifyUserSession } from '../../../utils/wxLogin.js'
export default {
  name: 'customBus',
  components: {
    'edit-info': EditInfo,
    'date-picker': DatePicker,
    'toast-alert': ToastAlert,
    'title-bar': TitleBar,
    'mock-remark': Remark
  },
  data() {
    return {
      isShowImgBg: true, // 控制title高度设置成功后显示
      isOverflow: false,
      isSubmit: true, // 控制是否能提交
      success: false,
      msgText: '',
      titleText: '', // 标题
      dateValue: {}, // 时间选择数据
      textareaValue: '',
      pickerConfig: [], // 选择器配置
      datePickerConfig: [
        {
          values: ['工作日', '节假日及周末', '全年'],
          defaultIndex: 0,
          textAlign: 'left'
        },
        {
          values: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'],
          defaultIndex: 8,
          textAlign: 'center'
        },
        {
          values: ['00', '05', '10', '15', '20', '25', '30', '35', '40', '45', '50', '55'],
          defaultIndex: 0,
          textAlign: 'center'
        }
      ],
      sitePickerConfig: []
    }
  },
  beforeRouteLeave(to, from, next) {
    // 页面返回的时候清空数据
    if (to.name === 'buyIndex') { // 回到首页清空信息
      this.dateValue = {}// 出发点、到达点
      this.pickerConfig = []// 出发、返程时间
      this.$refs.edit_textarea.setTextareaValue('')// 意见
      this.$refs.remark.mask.hide()// 隐藏弹窗
    }
    next()
  },
  computed: {
    mask() {
      return this.$refs.toastAlert.$refs.mask
    }
  },
  mounted() {
    this.activated()
    getStationList().then(res => {
      // console.error(res, 'res')
      this.sitePickerConfig = res
    })
    console.error(this.dateValue, 'dateValue~~~~~~~~~~~~~~~~~')
  },
  methods: {
    // 传入title 弹出选择器
    selectPicker(msg, timeArr, isAddTime) {
      // console.log(this.sitePickerConfig, this.datePickerConfig)
      // console.log(msg, timeArr)
      // 动态加载数组
      if (msg === '出发时间' || msg === '返程时间') {
        if (isAddTime) this.dateValue.isAddTime = false
        this.$set(this, 'pickerConfig', this.datePickerConfig)
      } else {
        this.$set(this, 'pickerConfig', this.sitePickerConfig)
      }
      // 将当前默认值下标赋值上去
      if (timeArr) {
        this.pickerConfig.map((item, index) => {
          item.defaultIndex = timeArr[index]
        })
      }
      this.titleText = msg
      this.$refs.datePicker.show()
    },
    // 获取选择器value
    getValue(dateValue) {
      if (dateValue.title === '到达地点') {
        this.dateValue.siteIndex = dateValue.indexArr
        this.$set(this.dateValue, 'siteInfo', dateValue.dateValueArr[0]) // 记录选择地点默认值
      } else {
        // 时间字符串拼接
        let dateTimeText = dateValue.dateValueArr[0] + ' ' + dateValue.dateValueArr[1] + ':' + dateValue.dateValueArr[2]
        // 添加出发和返程数据
        if (dateValue.title === '出发时间') {
          let obj = {
            dateStartTime: dateTimeText, // 记录出发时间
            dateStartTimeIndexArr: dateValue.indexArr, // 记录出发时间默认值
            dateStartTimeValueArr: dateValue.dateValueArr, // 记录出发信息
            deteStartTimeArrFirstValue: dateValue.indexArr[0] + 1 // 记录第一个值的values
          }
          this._objUpdate(obj, 'set', this.dateValue)
        } else {
          let obj = {
            dateEndTime: dateTimeText, // 记录返程时间
            dateEndTimeIndexArr: dateValue.indexArr, // 记录返程时间默认值
            dateEndTimeValueArr: dateValue.dateValueArr, // 记录返程信息
            dateEndTimeArrFirstValue: dateValue.indexArr[0] + 1 // 记录第一个值的values
          }
          this._objUpdate(obj, 'set', this.dateValue)
        }
      }
      this.dateValue = Object.assign(this.dateValue, dateValue)
    },
    // 提交onSubmit--验证
    onSubmit() {
      let msg
      this.dateValue.textareaValue = this.textareaValue
      if (!this.dateValue.startSite) {
        msg = '请选择出发地点'
        return this.$toastMsg(msg)
      }
      if (!this.dateValue.siteInfo) {
        msg = '请选择到达地点'
        return this.$toastMsg(msg)
      }
      if (!this.dateValue.dateStartTime) {
        msg = '请选择出发时间'
        return this.$toastMsg(msg)
      }
      if (this.dateValue.isAddTime) {
        msg = '请选择返程时间'
        return this.$toastMsg(msg)
      }
      verifyUserSession(this, this.submitCustomDemand()) // 校验用户授权信息是否有效
    },
    // 提交征集意见需求请求
    submitCustomDemand() {
      if (this.isSubmit) {
        this.isSubmit = false
        onAddCustomDemand(this.dateValue, this.dateValue.isAddTime).then(res => {
          // 验证后做处理
          this.msgText = '提交成功'
          this.success = true
          this.mask.show()
          this.onOverflow(true)
          this.reset()
          setTimeout(() => {
            this.$router.push({ name: 'buyIndex' })
          }, 500)
        }).catch((err) => {
          console.dir(err)
          // if (err.error.data.RSPCD === '000924') {
          //   msg = '出发时间应小于等于返回时间'
          //   this.$toastMsg(msg)
          // } else {
          this.msgText = '提交失败，请重新尝试'
          this.success = false
          this.isSubmit = true
          this.mask.show()
          this.onOverflow(true)
          // }
        })
        setTimeout(() => {
          this.mask.hide()
          this.onOverflow(false)
        }, 1500)
      }
    },
    // 删除返程
    clearDateEnd() {
      let obj = {
        dateEndTime: '',
        dateEndTimeIndexArr: '',
        dateEndTimeValueArr: '',
        dateEndTimeArrFirstValue: '',
        isAddTime: null
      }
      this._objUpdate(obj, 'delete', this.dateValue)
    },
    // 添加返程字段--用以控制弹窗验证
    addDateEnd() {
      this.dateValue.isAddTime = true // true为需要输入 false跳过
    },
    // 遍历对象 更新数据及视图--$set/$delete
    _objUpdate(obj, type, target) {
      for (let i in obj) {
        this['$' + type](target, i, obj[i])
      }
    },
    // 重置数据
    reset() {
      this.dateValue = {}
      this.$refs.edit_textarea.clearTextarea()
      this.isSubmit = true
    },
    // 获取textarea值
    getTextareaValue(val) {
      this.textareaValue = val
    },
    // 点击弹起textarea
    onRemark() {
      this.$refs.remark.mask.show()
      this.onOverflow(true)
      this.$refs.remark.setTextareaValue(this.textareaValue)
    },
    // 设置textarea值
    setTextareaValue(value) {
      this.$refs.edit_textarea.setTextareaValue(value)
    },
    // 禁止滚动 -- 用于弹起弹框时禁止滚动
    onOverflow(bool) {
      this.isOverflow = bool
    },
    // 设置高度
    // setHeight(titleBarHeight) {
    //   this.$nextTick(() => {
    //     let imgDom = document.querySelector('.img_bg')
    //     let wrapDom = document.querySelector('.wrap')
    //     // alert('titleBarHeight:' + titleBarHeight)
    //     let w = document.body.clientWidth / 10
    //     let ratio = titleBarHeight / w
    //     let ratioAdd = 1.94
    //     let ratioCal = 1.74
    //     let height
    //     if (ratio > ratioCal && ratio < ratioAdd) {
    //       // alert('ratio:' + ratio)
    //       height = titleBarHeight + 24
    //     } else {
    //       height = titleBarHeight
    //     }
    //     imgDom.style.marginTop = '-' + height + 'px'
    //     wrapDom.style.height = 'auto' // 为了不自动计算content高度
    //     this.isShowImgBg = true
    //   })
    // }
    activated() {
      this.$EventBus.$on('siteName', function (val) {
        // this.dateValue.startSite.NAME = val
        this.$set(this.dateValue, 'startSite', val)
      }.bind(this))
    }
  }
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
}
html,
body {
  height: 100%;
  background-color: #f2f5f6;
}
/* 修复css边距合并带来的问题 */
body {
  position: absolute;
  width: 100%;
}
.app_wrap {
  height: 100%;
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  overflow: hidden;
  overflow-y: auto;
}
.overflowHidden {
  overflow-y: hidden;
}
.customBus_content {
  padding: 0 32px;
  margin-top: -84px;
  box-sizing: border-box;
}
.btn_onSubmit {
  width: 686px;
  height: 72px;
  border: none;
  border-radius: 36px;
  color: #fff;
  background: linear-gradient(
    90deg,
    rgba(39, 132, 255, 1) 0%,
    rgba(78, 129, 250, 1) 100%
  );
}
.btn_onSubmit_wrap {
  padding: 68px 32px 100px;
}
.wrap .img_bg {
  margin-top: -80px;
  height: 440px;
  width: 750px;
}
</style>
